<template>
  <div class="box">
    <div class="period-message">
      <div class="tab-btn">
        <el-radio-group
          v-model="activePeriod"
          @change="changeTabs"
          size="small"
        >
          <el-radio-button
            v-for="(item, index) in radioButtons"
            :label="item.id"
            :key="index"
            >{{ item.label }}</el-radio-button
          >
        </el-radio-group>
      </div>
      <div class="content">
        <div class="title">
          <p>
            <span>{{ detail.course_name }}</span>
            <span class="active">第{{ detail.sort }}期</span>
            <span>主讲人：{{ detail.teacher_name }}</span>
            <span class="margin-left5 margin-right5"
              >课时数:{{ detail.completedlesson }}/{{
                detail.totallesson
              }}</span
            >
            <span>课程状态:{{ detail.status }} </span>
          </p>
          <p>
            <span>上课时间：{{ detail.date }}</span
            ><span class="margin-left10">{{ detail.time }}</span>
          </p>
        </div>
        <nice-table
          :data="classList"
          :showIndex="true"
          :columns="classColumns"
          :showBorder="false"
          :pagination="classPagination"
          @rowClick="rowClick"
          :highlightCurrentRow="true"
        >
          <el-table-column
            label="班级名称"
            align="center"
            width="200"
            slot="className"
          >
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                v-focus
                size="small"
                @blur="handleInputConfirm(scope.row)"
                maxlength="4"
                show-word-limit
              ></el-input>
              <div v-else>
                <el-button size="small" type="text">{{
                  scope.row.classes_name
                }}</el-button>
                <i
                  class="el-icon-edit"
                  @click.stop="editClassName(scope.row)"
                ></i>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="80"
            slot="opreation"
            fixed="right"
          >
            <template slot-scope="scope">
              <!-- <el-button size="small" type="text" @click.stop="deleteClassHandle(scope.row)" :disabled="!!scope.row.num">删除</el-button> -->
              <el-button
                size="small"
                type="text"
                @click.stop="deleteClassHandle(scope.row)"
                disabled
                >删除</el-button
              >
            </template>
          </el-table-column>
        </nice-table>
      </div>
      <el-button
        type="primary"
        @click="addClassHandle()"
        size="small"
        class="add-class-btn"
        >新增班级</el-button
      >
    </div>
    <div class="student-message">
      <div class="m-h3-btn-box">
        <h3>{{ detail.course_name }} 第{{ detail.sort }}期 {{ className }}</h3>
        <div class="u-btn-box">
          <el-button type="primary" @click="batchPeriod" size="small"
            >批量调期</el-button
          >
          <el-button type="primary" @click="batchClass" size="small"
            >批量调班</el-button
          >
        </div>
      </div>
      <nice-table
        :data="studentList"
        :showSelection="true"
        :columns="studentColumns"
        :showBorder="false"
        :pagination="studentPagination"
        @handleSelectionChange="handleSelectionChange"
        ref="classTable"
      >
        <el-table-column
          label="操作"
          align="center"
          width="100"
          slot="opreation"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              size="small"
              type="text"
              @click="adjustDateHandle(scope.row)"
              >调期</el-button
            >
            <el-button
              size="small"
              type="text"
              @click="adjustClassHandle(scope.row)"
              >调班</el-button
            >
          </template>
        </el-table-column>
      </nice-table>
    </div>
    <!-- 新增班级 -->
    <add-class
      v-if="addClassDialog"
      ref="addClass"
      @refreshDataList="getClassByPeriodId"
      :periodId="activePeriod"
      :courseId="courseId"
    ></add-class>
    <!-- 调班or调期-->
    <allocation-class
      v-if="classAllocationDialog"
      ref="classAllocation"
      :title="title"
      @refreshDataList="getClassByPeriodId()"
      :mode="mode"
      :periodList="periodList"
      :periodId="activePeriod"
      :courseId="courseId"
      :className="className"
      :multipleSelection="multipleSelection"
      :classId="classId"
    ></allocation-class>
  </div>
</template>
<script>
import AddClass from "./add-class.vue";
import AllocationClass from "./allocation-class";
import { tableUpdate } from "@/api/api.js";
import {
  getPeriodByCouseId,
  getPeriodDetail,
  getClassByPeriodId,
  deleteClass,
  getStudentByClassId
} from "@/api/user.js";
export default {
  name: "period-students",
  components: {
    AddClass,
    AllocationClass
  },
  data() {
    return {
      activePeriod: "",
      courseId: "",
      classId: "",
      detail: {},
      classList: [],
      radioButtons: [],
      periodList: [],
      classColumns: [
        {
          label: "学生数量",
          prop: "num"
        },
        {
          label: "辅导老师",
          prop: "tutor_name"
        }
      ],
      className: "",
      mode: "",
      inputValue: "",
      addClassDialog: false,
      classAllocationDialog: false,
      title: "",
      studentList: [],
      classPagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleClassCurrentChange,
        handleSizeChange: this.handleClassSizeChange
      },
      studentPagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleStudentCurrentChange,
        handleSizeChange: this.handleStudentSizeChange
      },
      studentColumns: [
        {
          label: "姓名",
          prop: "name"
        },
        {
          label: "联系方式",
          prop: "phone",
          width: 150,
          extends: [
            {
              clickFunction: val => {
                this.viewPhone(val);
              },
              isView: true
            }
          ]
        },
        {
          label: "线下学校",
          prop: "school_name"
        }
      ],
      multipleSelection: []
    };
  },
  directives: {
    focus: {
      inserted: function(el) {
        el.querySelector("input").focus();
      }
    }
  },
  activated() {
    this.courseId = this.$route.params.id;
    this.getDataList();
  },
  methods: {
    async getDataList() {
      let res = await getPeriodByCouseId({
        "nice_course_period.course_id": this.courseId
      });
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (data && data.code === 0) {
        this.radioButtons =
          data.data.list &&
          data.data.list.map(ele => {
            let frequency = ele.frequency ? JSON.parse(ele.frequency) : [];
            let week = "周" + this.$filterFrequency(frequency);
            let title = "第" + this.$convertNum(ele.sort) + "期" + " " + week;
            let label = "第" + ele.sort + "期";
            return { label: label, id: ele.id, title: title };
          });
        this.periodList =
          this.radioButtons &&
          this.radioButtons.map(ele => {
            return { label: ele.title, value: ele.id };
          });
        this.activePeriod = this.radioButtons[0].id;
        this.getPeriodDetail();
        this.getClassByPeriodId();
      } else {
        this.$message.error(data.msg);
      }
    },
    async getPeriodDetail() {
      let res = await getPeriodDetail({
        "nice_course_period.id": this.activePeriod
      });
      if (res[0]) {
        return;
      }
      if (res[1] && res[1].code === 0) {
        this.detail = res[1].data.list[0];
        this.detail.status =
          this.detail.status === 1
            ? "已发布"
            : this.detail.status === 2
            ? "已关闭"
            : "待发布";
        this.detail.date =
          this.detail.start_date.substring(0, 10) +
          "~" +
          this.detail.end_date.substring(0, 10);
        let frequency = this.detail.frequency
          ? JSON.parse(this.detail.frequency)
          : [];
        this.detail.time = "周" + this.$filterFrequency(frequency);
      } else {
        this.$message.error(res[1].msg);
      }
    },
    async getClassByPeriodId() {
      let res = await getClassByPeriodId({
        "nice_classes.period": this.activePeriod,
        "page.currPage": this.classPagination.pageNum,
        "page.pageSize": this.classPagination.pageSize
      });
      if (res[0]) {
        return;
      }
      if (res[1] && res[1].code === 0) {
        this.classPagination.total = res[1].data.pageList.totalCount;
        if (this.classPagination.total) {
          res[1].data.pageList.list.forEach(ele => {
            ele.inputVisible = false;
            ele.inputValue = "";
          });
        }
        this.classList = res[1].data.pageList.list;
        this.studentList = [];
        this.studentPagination.total = 0;
        if (this.classList && this.classList.length) {
          this.className = this.classList[0].classes_name;
          this.classId = this.classList[0].id;
          this.getStudentByClassId(this.classList[0].id);
        }
      } else {
        this.$message.error(res[1].msg);
      }
    },
    changeTabs(val) {
      this.getPeriodDetail();
      this.getClassByPeriodId();
    },
    addClassHandle() {
      this.addClassDialog = true;
      this.$nextTick(() => {
        this.$refs.addClass.init();
      });
    },
    batchPeriod() {
      if (!this.multipleSelection.length) {
        this.$alert("请选择需要调期的学生", "提示", {
          confirmButtonText: "关闭",
          callback: action => {}
        });
      } else {
        this.title = "批量调期";
        this.mode = "batchPeriod";
        this.initAllocationClassOrPeriod();
      }
    },
    batchClass() {
      if (!this.multipleSelection.length) {
        this.$alert("请选择需要调班的学生", "提示", {
          confirmButtonText: "关闭",
          callback: action => {}
        });
      } else {
        this.title = "批量调班";
        this.mode = "batchClass";
        this.initAllocationClassOrPeriod();
      }
    },
    initAllocationClassOrPeriod(row) {
      this.classAllocationDialog = true;
      this.$nextTick(() => {
        this.$refs.classAllocation.init(row);
      });
    },
    handleClassCurrentChange(val) {
      this.classPagination.pageNum = val;
      this.getClassByPeriodId();
    },
    handleClassSizeChange(val) {
      this.classPagination.pageSize = val;
      this.getClassByPeriodId();
    },
    handleStudentCurrentChange(val) {
      this.studentPagination.pageNum = val;
      this.getStudentByClassId(this.classId);
    },
    handleStudentSizeChange(val) {
      this.studentPagination.pageSize = val;
      this.getStudentByClassId(this.classId);
    },
    adjustDateHandle(row) {
      this.title = "调期";
      this.mode = "period";
      this.initAllocationClassOrPeriod(row);
    },
    adjustClassHandle(row) {
      this.title = "调班";
      this.mode = "class";
      this.initAllocationClassOrPeriod(row);
    },
    viewPhone(row) {
      this.studentList.forEach(ele => {
        if (ele.student_id !== row.student_id) {
          ele.isView = false;
        }
      });
      row.isView = !row.isView;
      this.studentList = [...this.studentList];
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    deleteClassHandle(row) {
      this.$confirm("确定进行删除操作？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteClass(row.id);
        })
        .catch(() => {});
    },
    async deleteClass(id) {
      let res = await deleteClass({
        "nice_classes.enable": "1",
        "nice_classes.class_id": id
      });
      if (res[0]) {
      }
      let data = res[1];
      if (data && data.code === 0) {
        this.$message.success("删除班级成功！");
        this.getClassByPeriodId();
      } else {
        this.$message.error(data.msg);
      }
    },
    async handleInputConfirm(row) {
      if (!row.inputValue) {
        this.$message.error("请输入班级名称");
        return false;
      }
      if (row.inputValue.length > 4) {
        this.$message.error("只能输入4个字符");
        return false;
      }
      if (row.inputValue) {
        row.inputVisible = false;
        let res = await tableUpdate([
          {
            table_name: "nice_classes",
            update: [
              {
                classes_name: row.inputValue
              }
            ],
            where: [
              {
                id: row.id
              }
            ]
          }
        ]);
        if (res[0]) {
          return;
        }
        if (res[1] && res[1].code === 0) {
          this.$message({
            message: "编辑成功",
            type: "success",
            duration: 1500,
            onClose: () => {
              row.classes_name = row.inputValue;
              // this.getClassByPeriodId()
            }
          });
        } else {
          this.$message.error(res[1].msg);
        }
      }
    },
    editClassName(row) {
      row.inputValue = row.classes_name;
      this.classList.forEach(ele => {
        ele.inputVisible = false;
      });
      row.inputVisible = true;
    },
    rowClick(row) {
      this.classId = row.id;
      this.className = row.classes_name;
      this.getStudentByClassId(row.id);
    },
    async getStudentByClassId(id) {
      let res = await getStudentByClassId({
        "nice_classes_student.class_id": id,
        "page.currPage": this.studentPagination.pageNum,
        "page.pageSize": this.studentPagination.pageSize
      });
      if (res[0]) {
      }
      let data = res[1];
      if (data && data.code === 0) {
        data.data.pageList.list &&
          data.data.pageList.list.forEach(ele => {
            ele.isView = false;
          });
        this.studentList = data.data.pageList.list;
        this.studentPagination.total = data.data.pageList.totalCount;
      } else {
        this.$message.error(data.msg);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.box {
  display: flex;
  .period-message {
    width: 500px;
    .tab-btn {
      display: flex;
      justify-content: space-between;
    }
    .content {
      margin-top: 20px;
      border-radius: 5px;
      .title {
        padding: 15px;
        background: #ccc;
        font-size: 12px;
        .active {
          color: #3e83f8;
          margin: 0px 5px;
        }
      }
    }
    .add-class-btn {
      margin: 20px 0px;
      width: 100%;
    }
  }
  .student-message {
    flex: 1;
    margin-left: 30px;
    overflow: auto;
  }
}
</style>
